import 'package:enjoy_plus/models/login_model.dart';
import 'package:enjoy_plus/utils/eventbus.dart';
import 'package:enjoy_plus/utils/http.dart';
import 'package:enjoy_plus/utils/logger.dart';
import 'package:enjoy_plus/utils/toast.dart';
import 'package:enjoy_plus/utils/token.dart';
import 'package:flutter/material.dart';
import 'dart:async';

import 'package:tdesign_flutter/tdesign_flutter.dart';

class Login extends StatefulWidget {
  const Login({super.key});

  @override
  State<Login> createState() => _LoginState();
}

class _LoginState extends State<Login> {
  // 1. 实现倒计时
  int _countdown = 60;
  bool _isCountingDown = false;
  Timer? _timer;
  void _startCountdown() {
    if (_isCountingDown) {
      return;
    }
    _isCountingDown = true;
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      setState(() {
        if (_countdown > 0) {
          _countdown--;
        } else {
          _isCountingDown = false;
          _countdown = 60;
          timer.cancel();
        }
      });
    });
  }

  final TextEditingController _phoneController = TextEditingController();
  final TextEditingController _codeController = TextEditingController();

// 2. 获取验证码
  void _getVerificationCode() async {
    // 2.1 校验手机号
    if (_phoneController.text.isEmpty) {
      return ToastUtil.showError('请输入手机号码');
    }

    RegExp regExp = RegExp(r'^1[3-9]\d{9}$');
    if (!regExp.hasMatch(_phoneController.text)) {
      return ToastUtil.showError('请输入正确的手机号码');
    }

    // 2.2 调用获取验证码接口
    var res = await http.get<CodeModel>('/code',
        params: {
          'mobile': _phoneController.text,
        },
        fromJson: (json) => CodeModel.fromJson(json));
    if (res.code != 10000) return ToastUtil.showError('获取验证码失败');
    ToastUtil.showSuccess('验证码已发送');

    // 延迟执行
    Future.delayed(const Duration(seconds: 2), () {
      _codeController.text = res.data.code;
      ToastUtil.showSuccess('验证码: ${res.data.code}');
    });

    // 2.3 开始倒计时
    _startCountdown();
  }

  // 3. 提交登录信息
  void _submit() async {
    // 3.1 校验手机号
    if (_phoneController.text.isEmpty) {
      return ToastUtil.showError('请输入手机号码');
    }

    RegExp regExp = RegExp(r'^1[3-9]\d{9}$');
    if (!regExp.hasMatch(_phoneController.text)) {
      return ToastUtil.showError('请输入正确的手机号码');
    }

    // 3.2 校验验证码
    if (_codeController.text.isEmpty) {
      return ToastUtil.showError('请输入验证码');
    }
    if (_codeController.text.length != 6) {
      return ToastUtil.showError('请输入6位验证码');
    }
    RegExp regExp2 = RegExp(r'^\d{6}$');
    if (!regExp2.hasMatch(_codeController.text)) {
      return ToastUtil.showError('请输入6位验证码');
    }

    // 3.3 调用登录接口
    TDToast.showLoading(context: context, text: '登录中...');
    var res = await http.post<LoginResponseModel>('/login',
        data: {
          'mobile': _phoneController.text,
          'code': _codeController.text,
        },
        fromJson: (json) => LoginResponseModel.fromJson(json));
    TDToast.dismissLoading();
    if (res.code != 10000) return ToastUtil.showError('登录失败');

    // 3.4 存储token
    TokenManager().saveToken(res.data.token);
    logger.d('token: ${res.data.token}');
    ToastUtil.showSuccess('登录成功');

    // 3.5 返回到上一页
    _timer!.cancel(); // 注意清除定时器
    Navigator.pop(context);

    // 3.6 通知个人中心重新获取数据
    eventBus.fire(RefreshMine());
  }

  @override
  void initState() {
    super.initState();
    _phoneController.text = '18811451419';
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        centerTitle: true,
        title: const Text('登录'),
        leading: IconButton(
          onPressed: () => Navigator.pop(context),
          icon: const Icon(Icons.arrow_back_ios),
        ),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const SizedBox(height: 6),
            const Text('登录',
                style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
            const SizedBox(height: 10),
            const Text('加入享+，让生活更轻松'),
            const SizedBox(height: 24),
            Row(
              children: [
                Expanded(
                  child: TextField(
                    controller: _phoneController,
                    keyboardType: TextInputType.phone,
                    maxLength: 11,
                    style: const TextStyle(fontSize: 16),
                    decoration: const InputDecoration(
                      labelText: '手机号',
                      labelStyle: TextStyle(
                          color:
                              Color.fromARGB(255, 69, 127, 158)), // 焦点后提示词的颜色
                      focusedBorder: UnderlineInputBorder(
                        borderSide: BorderSide(
                            color:
                                Color.fromARGB(255, 69, 127, 158)), // 焦点后线条颜色
                      ),
                    ),
                  ),
                ),
                const SizedBox(width: 10),
                //获取验证码
                ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.white,
                    shadowColor: Colors.transparent,
                    foregroundColor: const Color.fromARGB(255, 85, 145, 175),
                    minimumSize: const Size(100, 50),
                  ),
                  onPressed: _getVerificationCode,
                  child: _isCountingDown
                      ? Text('$_countdown s后重新获取',
                          style: const TextStyle(color: Colors.grey))
                      : const Text('获取验证码'),
                ),
              ],
            ),
            const SizedBox(height: 10),
            TextField(
              controller: _codeController,
              keyboardType: TextInputType.number,
              maxLength: 6,
              style: const TextStyle(fontSize: 16),
              decoration: const InputDecoration(
                labelText: '验证码',
                labelStyle: TextStyle(
                    color: Color.fromARGB(255, 69, 127, 158)), // 焦点后提示词的颜色
                focusedBorder: UnderlineInputBorder(
                  borderSide: BorderSide(
                      color: Color.fromARGB(255, 69, 127, 158)), // 焦点后线条颜色
                ),
              ),
            ),
            const SizedBox(height: 6),
            const Text('未注册手机号经验证后将自动登录',
                style: TextStyle(color: Colors.grey, fontSize: 12)),
            const SizedBox(height: 36),
            ElevatedButton(
                onPressed: _submit,
                child: const Text('登录'),
                style: ElevatedButton.styleFrom(
                    backgroundColor: const Color(0xff5690AF),
                    foregroundColor: Colors.white,
                    fixedSize: const Size(double.infinity, 36),
                    minimumSize: const Size(double.infinity, 36))),
          ],
        ),
      ),
    );
  }
}
